﻿using AutoMapper;
using B.S.Filtration.Domain;
using B.S.Filtration.ErrorCode;
using B.S.Filtration.Read.Api.Application.Command.ProcessMonitoringCommand;
using MediatR;
using SqlSugar;

namespace B.S.Filtration.Read.Api.Application.CommandHander.ProcessMonitoringHandler
{
    public class GetProcessMonitoringhandler : IRequestHandler<GetProcessMonitoringCommand, APIResult<APIPaging<ProcessMonitoring>>>
    {

        private readonly ISqlSugarClient db;
        private readonly IMapper mapper;
        public GetProcessMonitoringhandler(ISqlSugarClient db, IMapper mapper)
        {
            this.db = db;
            this.mapper = mapper;
        }
        public async Task<APIResult<APIPaging<ProcessMonitoring>>> Handle(GetProcessMonitoringCommand request, CancellationToken cancellationToken)
        {
            APIResult<APIPaging<ProcessMonitoring>> reat = new APIResult<APIPaging<ProcessMonitoring>>();
            var listtt = await db.Queryable<ProcessMonitoring>().Where(x => !x.IsDel).ToListAsync();

            if (!string.IsNullOrEmpty(request.equipment_name))
            {
                listtt = listtt.Where(x => x.equipment_name.Contains(request.equipment_name)).ToList();
            }
            if (!string.IsNullOrEmpty(request.equipment_number))
            {
                listtt = listtt.Where(x => x.equipment_number.Contains(request.equipment_number)).ToList();
            }
            if (!string.IsNullOrEmpty(request.equipment_status))
            {
                listtt = listtt.Where(x => x.equipment_status.Contains(request.equipment_status)).ToList();
            }
            if (!string.IsNullOrEmpty(request.operators))
            {
                listtt = listtt.Where(x => x.operators.Contains(request.operators)).ToList();
            }
            if (request.operation_time != null)
            {
                listtt = listtt.Where(x => x.operation_time.Date == request.operation_time.Value.Date).ToList();
            }
            int totalCount = listtt.Count();
            int PageCount = (int)Math.Ceiling(totalCount * 1.0 / request.pageSize);
            listtt = listtt.OrderByDescending(a => a.id).Skip((request.pageindex - 1) * request.pageSize).Take(request.pageSize).ToList();
            APIPaging<ProcessMonitoring> paging = new APIPaging<ProcessMonitoring>()
            {
                TotalCount = totalCount,
                TotalPage = PageCount,
                list = listtt.ToList(),

            };

            reat.code = APIResultCode.success;
            reat.msg = "过程监控显示成功";
            reat.data = paging;
            return reat;
        }
    }
}
